package com.haiheng.commonlibrary

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.NavHostFragment
import com.haiheng.common.activity.RouterActivity
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.RourePage
import com.haiheng.common.constant.RourePath
import com.haiheng.commonlibrary.databinding.ActivityMainBinding
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.dialog.PasswordDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.library_base.utils.GpioUtils
import com.haiheng.library_base.utils.KeyboardUtils

class MainActivity : RouterActivity() {


    var binding: ActivityMainBinding? = null

    override fun controllerId(): Int {
        return R.id.nav_host_fragment_main
    }
    private val observer = Observer<MsgEvent> { msgEvent ->

    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when(msgEvent?.code){
            MsgCode.MSG_ROBOT_CODE->{

            }
            MsgCode.MSG_ROBOT_SOTOP_NAVIGATION_CODE->{

            }
        }
    }


    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observeForever(observer)
        }
    }

    override fun navigation(name: RourePage, bundle: Bundle?) {
        when(name){
            RourePage.MAIN ->popBackStack(R.id.main,false)
            RourePage.SETTING_PAGE ->navigate(RourePath.SETTING_PAGE_FRAGMENT,bundle)
        }
    }

    override fun setTitleBgColor(color: Int) {
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTheme(R.style.AppTheme)
        window.setFormat(PixelFormat.TRANSLUCENT)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(binding!!.root)
        LogUtils.d("开始初始化信息")
        observEven()
        binding?.vSetting?.setOnClickListener {
            if (FastClickUtil.isFastFiveClick(binding?.vSetting?.id!!,1000)){
                var dialog = PasswordDialog.newInstance()
                dialog.setOnPasswordLisener(object : PasswordDialog.OnPasswordLisener{
                    override fun onRightClick(title: String?, passwod: String?) {
                        if (passwod == AppConstant.getAdminPassword()) {
                            navigation(RourePage.SETTING_PAGE,null)
                            dialog.dismiss()
                        } else {
//                            ToastUtils.showShort(getString(R.string.password_error))
                            dialog.clearText()
                        }
                    }
                })
                dialog.show(supportFragmentManager)
            }
        }

        requestPermissions(99)
//        if (AppConstant.isYSK3588Board()){//3588板子获取雷达权限
//            GpioUtils.upgradeRootPermissionForExport();
//        }
        startReportService()
    }

    override fun popBackStackByPage(page: RourePage, inclusive: Boolean) {
        when(page){
            RourePage.SETTING_PAGE ->{
                popBackStack(R.id.setting, inclusive)
            }
        }
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (event?.keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_DOWN) {
            val pressedKey = event.unicodeChar.toChar()
            LogUtils.d("pressedKey:${pressedKey}")
        }
        return super.dispatchKeyEvent(event)
    }
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.getAction() == MotionEvent.ACTION_DOWN) {
            var v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                KeyboardUtils.hideSoftInput(this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationOnScreen(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.rawX > left && event.rawX < right && event.rawY > top && event.rawY < bottom)
        }
        return false
    }


    @Suppress("UNCHECKED_CAST")
    fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
        val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

        navHostFragment.childFragmentManager.fragments.forEach {
            if (fragmentClass.isAssignableFrom(it.javaClass)) {
                return it as F
            }
        }

        return null
    }


    override fun onPause() {
        LogUtils.d("ReportService  activity onPause")
        super.onPause()
    }
    override fun onStop() {
        LogUtils.d("ReportService  activity onStop")
        super.onStop()
        stopService()
    }
    override fun onDestroy() {
        LogUtils.d("ReportService  activity onDestroy")
        super.onDestroy()
        stopService()
    }

    fun startReportService(){
        LogUtils.d("ReportService 启动服务")
//        val intent = Intent(this, ReportService::class.java)
//        startService(intent)
    }

    fun stopService(){
        LogUtils.d("ReportService 停止服务")
        // 停止服务
//        val intent = Intent(this, ReportService::class.java)
//        stopService(intent)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var flag = false
        for (i in permissions.indices) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                flag = true
            }
        }
    }

    // 请求权限
    fun requestPermissions(requestCode: Int) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                val permissionArray = arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.REORDER_TASKS,
                    Manifest.permission.GET_TASKS,
                    Manifest.permission.READ_PHONE_STATE
                )

                val list = ArrayList<String>()
                for (permission in permissionArray) {
                    if (ActivityCompat.checkSelfPermission(
                            this,
                            permission
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        list.add(permission)
                    }
                }
                // 是否应该显示权限请求
                if (list.isNotEmpty()) {
                    val permissionsToRequest = list.toTypedArray()
                    requestPermissions(permissionsToRequest, requestCode)

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            LogWriter.d("权限获取失败${e}")
        }
    }

}

